# -*- coding: utf8 -*-
# Create your views here.
from django.http import HttpResponse
#import outland.list.model as om
from outland.list.models import *
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.conf import settings
from django import forms
from django.contrib import auth
from django.http import HttpResponseRedirect

def listMenuJson(request, qShop=''):
    menuList = Menu.objects.filter(shop=Shop.objects.get(name=qShop)).values_list('name',flat=True)
    data = simplejson.dumps({'name_list':list(menuList)},ensure_ascii=False)
    return HttpResponse(data)

def listShopJson(request, qCategory=''):
    shopList = Shop.objects.filter(category=ShopCategory.objects.get(name=qCategory)).values_list('name',flat=True)
    data = simplejson.dumps({'name_list':list(shopList)},ensure_ascii=False)
    return HttpResponse(data)

def listCategoryJson(request):
    cateList = ShopCategory.objects.values_list('name',flat=True)
    data = simplejson.dumps({'name_list':list(cateList)},ensure_ascii=False)
    return HttpResponse(data)

def listShopHtml(request, qCategory=''):
    shopList = Shop.objects.filter(category=ShopCategory.objects.get(id=qCategory))
    return render_to_response('list/ShopList.html',{'shopList':shopList});

def listMenuHtml(request, qShop=''):
    shop=Shop.objects.get(id=qShop)
    menuList = Menu.objects.filter(shop=shop)
    return render_to_response('list/MenuList.html',{'menuList':menuList,'shop':shop});

def ShopDescHtml(request, qShop=''):
    shop=Shop.objects.get(id=qShop)
    return HttpResponse('<b>'+shop.name+'</b>'+'<br /><br />'+str(shop.desc));

def ShopCommentJson(request,qShop):
    comment = ShopComment.objects.filter(shop=qShop)
    
    c=[]
    for i in comment:
        c.append(i.to_dict())
    json = simplejson.dumps({"comment":c,"shop":qShop},ensure_ascii=False)
    return HttpResponse(json)

def PostComment(request):
    if request.method == 'POST':
        d = my_dict(request.POST)
        d['user'] =  request.user.id
        d['ip'] =  request.META['REMOTE_ADDR']
        form = ShopCommentForm(d)
        if form.is_valid():
            form.save()
            return HttpResponse('ok')
        else:
            return HttpResponse(str(d))
    else:
        return HttpResponse('POST only.')




def save(request):
    d = {} 
    s = ''
    for i in request.GET:
        d[i] = request.GET[i];
        s += '(%s,%s)'%(i,request.GET[i])
    data = simplejson.dumps({'s':s},ensure_ascii=False)
    return HttpResponse(data)

def order(request):
	if request.user.is_authenticated() and request.method == 'POST' and request.POST.has_key('menu') and request.POST.has_key('price'):
			o = Order(user=request.user, price = int(request.POST['price']));
			f = open('/tmp/aaaa','w');
			f.write('aaaa\n');
			f.close();
			o.save();

			m_list = list(int(x) for x in request.POST['menu'].split('|') if x)
			
			m_filter = Menu.objects.filter(id__in=m_list);
			for i in m_filter:
				o.menu.add(i);

			o.save();

			return HttpResponse('Success');
	else:
		return HttpResponse('login');

def listShop(request,qCategory='',qShop=''):
    return render_to_response('list/ListMain.html',{'is_login':request.user.is_authenticated()})



def login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Correct password, and the user is marked "active"
            auth.login(request, user)
            # Redirect to a success page.
            request.session["member_id"] = user.id
            return HttpResponseRedirect("/outland/list")
        else:
            # Show an error page
            return HttpResponse("Login failed")
    else:
        return HttpResponse("invalid. POST only")

def login_view(request):
    form = CustomUserForm()
    return render_to_response('list/Login.html',{'form':form})

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/outland/list/')
    
def my_dict(postdict):
    d = dict()
    for k in postdict.keys():
        d[k] = postdict[k]
    return d
